package com.liuhan.house.controller;

import com.liuhan.house.common.Constants;
import com.liuhan.house.pojo.Agency;
import com.liuhan.house.pojo.User;
import com.liuhan.house.service.AgencyService;
import com.liuhan.house.service.FileService;
import com.liuhan.house.service.UserService;
import com.liuhan.house.util.PropertiesUtil;
import com.liuhan.house.util.ResultMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;
    @Autowired
    private AgencyService agencyService;

    /**
     * 跳转到注册界面
     */
    @RequestMapping("page/register")
    public String pageRegister(ModelMap modelMap) {
        // 查询出来经纪机构列表
        List<Agency> agencyList = agencyService.selectCompanyName();
        modelMap.put("agencyList", agencyList);
        return "/user/accounts/register";
    }

    /**
     * 注册用户信息
     */
    @RequestMapping("user/register")
    public String addUser(User user, @RequestParam(value = "file", required = false) MultipartFile[] file, HttpServletRequest request, ModelMap modelMap) {
        // 图片上传到地址服务器
        String path = request.getSession().getServletContext().getRealPath("upload");
        StringBuffer buffer = new StringBuffer();
        for (MultipartFile files : file) {
            String targetFileName = fileService.upload(files, path);
            String url = PropertiesUtil.getProperty("FTP_SERVER_HTTP_PREFIX") + targetFileName;
            buffer.append(url + ",");
        }
        int index = buffer.lastIndexOf(",");
        String urls = buffer.substring(0, index);
        user.setUserHeadImg(urls);

        if (userService.addUser(user)) {
            modelMap.put("email", user.getUserEmail());
            return "/user/accounts/registerSubmit";
        } else {
            return "/user/accounts/register";
        }

    }

    /**
     * 校验用户邮箱
     * @param key
     * @return
     */
    @RequestMapping("user/verify")
    public String userVerify(String key) {
        boolean result = userService.enable(key);
        if (result) {
            return "redirect:/homepage/index?" + ResultMsg.successMsg("激活成功").asUrlParams();
        } else {
            return "redirect:/accounts/register?" + ResultMsg.errorMsg("激活失败，请重新注册").asUrlParams();
        }
    }

    /**
     * 用户登录
     */
    @RequestMapping("user/login")
    public String userLogin(HttpServletRequest request) {
        String userEmail = request.getParameter("username");
        String password = request.getParameter("password");
        String target = request.getParameter("target");
        // 密码账号一个为空，判定为跳转到登录页
        if (userEmail == null || password == null) {
            request.setAttribute("target", target);
            return "/user/accounts/login";
        }
        User user = userService.verifyUser(userEmail, password);
        if (user == null) {
            return "redirect:/user/login?target=" + target + "&userEmail=" + userEmail + "&" + ResultMsg.errorMsg("用户名或密码错误").asUrlParams();
        } else {
            HttpSession session = request.getSession(true);
            session.setAttribute(Constants.PLAIN_USER_ATTRIBUTE, user);
            session.setAttribute(Constants.USER_ATTRIBUTE, user);
            if (user.getUserType() == 2) {
                session.setAttribute("addHouse", true);
            }
            return StringUtils.isNoneBlank(target) ? "redirect:" + target : "redirect:/homepage/index";
        }
    }

    /**
     * 用户登出接口
     */
    @RequestMapping("user/logout")
    public String userLogout(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        session.invalidate();
        return "redirect:/homepage/index";
    }

    /**
     * 个人信息页面跳转
     */

    @RequestMapping("page/user/profile")
    public String pageUserProfile() {
        return "/user/accounts/profile";
    }

    /**
     * 个人信息修改
     * @param request
     * @return
     */
    @RequestMapping("user/profile")
    public String userProfile(HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute("user");
        if (user.getUserEmail() == null) {
            return "redirect:/user/login?" + ResultMsg.errorMsg("请进行登录").asUrlParams() ;
        }
        String username = request.getParameter("name");
        String phone = request.getParameter("phone");
        String aboutme = request.getParameter("aboutme");
        userService.updateUserInformation(username, phone, aboutme, user.getUserEmail());
        User newUserInfo = userService.getUserByEmail(user.getUserEmail());
        // 更新用户信息
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.PLAIN_USER_ATTRIBUTE, newUserInfo);
        session.setAttribute(Constants.USER_ATTRIBUTE, newUserInfo);
        return "success/success";
    }

    /**
     * 密码修改
     */
    @RequestMapping("user/editor/password")
    public String editorPassword(HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute("user");
        if (user == null) {
            return "redirect:/user/login?" + ResultMsg.errorMsg("请进行登录").asUrlParams() ;
        }
        String password = request.getParameter("password");
        User user1 = userService.getUserByEmailAndPassword(user.getUserEmail(), password);
        if (user1 == null) {
            return "redirect:/user/profile?" + ResultMsg.errorMsg("旧密码输入有误").asUrlParams();
        }
        String newPassword = request.getParameter("newPassword");
        userService.editorPassword(newPassword, user.getUserEmail());
        request.getSession(true).invalidate();
        return "redirect:/user/login?" + ResultMsg.errorMsg("请进行登录").asUrlParams() ;
    }

}
